#include<iostream>
#include<cassert>
#include<cstring>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>

using namespace std;

#define MAX 1024

int main()
{
    //1.创建管道
    int pipefd[2]={0};
    int n=pipe(pipefd);
    assert(n==0);
    (void)n;
    std::cout<<"pipefd[0]"<<":"<<pipefd[0]<<","<<"pipefd[1]"<<":"<<pipefd[1]<<std::endl;
    
    //2.创建进程
    pid_t id=fork();
    if(id<0)
    {
        perror("fork fail");
        return 1;
    }
    if(id==0)
    {
        //child
        close(pipefd[0]);
        int cnt=0;
        while(true)
        {
            char message[MAX];
            snprintf(message,sizeof(message),"hello father,I am child,pid: %d,cnt: %d",getpid(),cnt);
            cnt++;
            write(pipefd[1],message,strlen(message));
            sleep(1);
        }
        std::cout<<"child close w points"<<std::endl;
        exit(0);
    }
    //father
    close(pipefd[1]);
    char buffer[MAX];
    while(true)
    {
        ssize_t n=read(pipefd[0],buffer,sizeof(buffer)-1);
        if(n>0)
        {
            buffer[n]='\0';
            std::cout<<getpid()<<","<<"child say: "<<buffer<<" to me!"<<std::endl;
        }
        else if(n==0)
        {
            std::cout<<"child quit,me too!"<<std::endl;
            break;
        }
       std::cout<<"father return val(n): "<<n<<std::endl;
       sleep(1);
       break;

    }
    std::cout<<"father close r point!"<<std::endl;
    close(pipefd[0]);
    sleep(5);
    int status=0;
    pid_t rid=waitpid(id,&status,0);
    if(rid==id)
    {
        std::cout<<"wait success,child exit sig: "<<(status&0x7f)<<std::endl;
    }
    return 0;
}
